<template>
  <div class="container">
    <van-list
      v-model="loading"
      :finished="finished"
      @load="onLoad"
      class="news-list"
    >
      <van-checkbox-group
        v-model="checkedGoods"
        ref="checkboxGroup"
      >
        <check-goods
          :item="item"
          v-for="(item, index) in list"
          :key="index"
          @click="onClickView"
        >
          <van-checkbox
            :name="item"
            checked-color="#ff6600"
          />
        </check-goods>
      </van-checkbox-group>

      <van-cell-group
        class="mv-15"
        v-if="invalidGoods.length>0"
      >
        <van-cell
          title="无效商品"
          value-class="text-right"
        >
          <van-button
            size="mini"
            type="warning"
            round
            plain
            @click="onClearInvalid"
          >清空失效商品</van-button>
        </van-cell>
        <check-goods
          :item="item"
          v-for="(item, index) in invalidGoods"
          :key="index"
          @click="onClickView"
        >
          <label class="label label-sm label-round label-default">失效</label>
          <template slot="price">
            <span class="text-default">{{item.invalid_tips}}</span>
          </template>
          <template slot="price-right">
            <van-button
              size="mini"
              type="warning"
              round
              plain
            >找相似</van-button>
          </template>
        </check-goods>
      </van-cell-group>

    </van-list>

    <van-submit-bar
      :price="totalPrice"
      :disabled="!checkedGoods.length"
      :button-text="submitBarText"
      @submit="onSubmit"
    >
      <van-checkbox
        v-model="checkedAll"
        @click="toggleAll"
        :disabled="!list.length"
        checked-color="#ff6600"
      >全选</van-checkbox>
    </van-submit-bar>
    <div class="placeholder"></div>
  </div>
</template>

<script>
import {
  Tag,
  Col,
  Icon,
  Cell,
  CellGroup,
  Popup,
  Sku,
  Button,
  Panel,
  PullRefresh,
  Lazyload,
  List,
  Checkbox,
  CheckboxGroup,
  Card,
  Stepper,
  SubmitBar,
  GoodsAction,
  GoodsActionButton,
  GoodsActionIcon,
  Toast
} from 'vant'
import CheckGoods from '@/components/checkGoods'

export default {
  components: {
    CheckGoods,
    [Tag.name]: Tag,
    [Col.name]: Col,
    [Icon.name]: Icon,
    [Cell.name]: Cell,
    [CellGroup.name]: CellGroup,
    [Panel.name]: Panel,
    [Popup.name]: Popup,
    [Sku.name]: Sku,
    [Button.name]: Button,
    [PullRefresh.name]: PullRefresh,
    [Lazyload.name]: Lazyload,
    [List.name]: List,
    [Card.name]: Card,
    [Stepper.name]: Stepper,
    [Checkbox.name]: Checkbox,
    [SubmitBar.name]: SubmitBar,
    [GoodsAction.name]: GoodsAction,
    [GoodsActionButton.name]: GoodsActionButton,
    [GoodsActionIcon.name]: GoodsActionIcon,
    [CheckboxGroup.name]: CheckboxGroup
  },

  data () {
    return {
      showBase: false,
      closeOnClickOverlay: true,
      editmode: false,
      list: [],
      loading: false,
      finished: false,
      count: 0,
      show: false,
      meta: {
        totalCount: 0,
        pageCount: 0,
        currentPage: 0,
        perPage: 0
      },
      checkedAll: false,
      checkedGoods: [],
      invalidGoods: []
    }
  },

  created () {
    console.group('Cart')
    console.log('state', this.$store.state.settings.backRoute)
    console.groupEnd('Cart')
  },

  watch: {
    checkedGoods: {
      handler (cv, ov) {
        console.log('[checkedGoods]', cv)
        console.log('[checkedGoods.length]', this.checkedGoods.length)
        console.log('[list.length]', this.list.length)
        if (this.checkedGoods.length === this.list.length) {
          this.checkedAll = true
        } else {
          this.checkedAll = false
        }
      },
      deep: true
    },
    paymode: {
      handler (curVal, oldVal) {
        console.log('当前编辑状态：', curVal)
        console.log('之前编辑状态：', oldVal)
      },
      deep: true
    }
  },

  beforeRouteLeave (to, from, next) {
    // async
    // 导航离开该组件的对应路由时调用
    console.group('Cart beforeRouteLeave')
    // next(false)
    if (!/\/login|\/authorize/g.test(to.path)) {
      let params = this.checkedGoods.map(item => item.id)
      console.log('[params]', params)
      this.$http.shop.batchUpdateCartStatus({ items: params })
    }
    next()
    console.groupEnd('Cart beforeRouteLeave')
  },

  computed: {
    submitBarText () {
      const count = this.checkedGoods.length
      return '结算' + (count ? '(' + count + ')' : '')
    },

    totalPrice () {
      return this.checkedGoods.reduce((accumulator, item) => {
        console.log('[accumulator]', accumulator)
        console.log('[item]', item)
        return accumulator + item.price * item.num * 100
      }, 0)
    }
  },

  methods: {
    toggleAll () {
      if (this.checkedGoods.length !== this.list.length) {
        this.$refs.checkboxGroup.toggleAll(true)
      } else {
        this.$refs.checkboxGroup.toggleAll(false)
      }
    },
    onLoad () {
      this.$http.shop
        .cart()
        .then(response => {
          let data = response.data
          data.forEach((item, index) => {
            if (item.status) {
              this.list.push(item)
              if (item.checked) {
                this.checkedGoods.push(item)
              }
            } else {
              this.invalidGoods.push(item)
            }
          })
          this.loading = false
          this.finished = true
        })
    },
    onCheckSku (id) {
      this.axios
        .get('/shop/spu/' + id, {
          headers: { FastMode: true }
        })
        .then(response => {
          this.sku = response.data
          this.showBase = true
        })
        .catch(function (error) {
          console.log(error)
        })
    },
    onClickView (item) {
      this.$router.push({
        name: 'goods/:id',
        params: {
          id: item.product_id
        }
      })
    },
    onBuyClicked (data) {
      Toast(JSON.stringify(data))
    },
    changeNumber (id, num) {
      console.log(id, num)
      // this.axios
      //   .get('/shop/cart/change', {
      //     params: { id: id, num: num },
      //     headers: { FastMode: true }
      //   })
      //   .then(response => {
      //     this.sku = response.data
      //     this.showBase = true
      //   })
      //   .catch(function (error) {
      //     console.log(error)
      //   })
    },
    onClickMoveToCollect () {
      Toast('移入收藏' + JSON.stringify(this.checkedGoods))
    },
    onDelete () {
      Toast('删除' + JSON.stringify(this.checkedGoods))
    },
    onRemove (id, index) {
      this.axios
        .get('/shop/cart/remove', {
          params: { id: id },
          headers: { FastMode: true }
        })
        .then(response => {
          if (response.data) {
            this.list.splice(index, 1)
          } else {
            Toast('移除失败')
          }
        })
        .catch(function (error) {
          console.log(error)
        })
    },
    arrayUnique (arr) {
      let result = []
      let hash = {}
      for (let i = 0, elem; (elem = arr[i]) != null; i++) {
        if (!hash[elem.id]) {
          result.push(elem)
          hash[elem.id] = true
        }
      }
      return result
    },
    formatPrice (price) {
      return price.toFixed(2)
    },
    formatDescription (sku, stock) {
      if (stock > 0) {
        return sku
      }
      return sku + '（库存不足）'
    },
    onSubmit () {
      let goods = this.checkedGoods.map(({ id, num }) => ({ id, num }))
      console.log('goods', goods)
      this.$http.shop
        .cartBalance(goods)
        .then(response => {
          if (response.data) {
            this.$router.push({
              path: '/balance'
            })
          }
        })
        .catch(function (error) {
          console.log(error)
          Toast('结算准备失败')
        })
    },
    onClearInvalid () {
      this.$http.shop
        .clearCart()
        .then(response => {
          console.log(response)
        })
        .catch(function (error) {
          console.log(error)
          Toast('重置失败')
        })
    },
    changeState (item) {
      this.checkedGoods = []
      if (item) {
        this.list.forEach((value, index) => {
          if (value.status) {
            this.checkedGoods.push(value.id)
          }
        })
      } else {
        this.checkedGoods = this.isIndeterminate
      }
      this.isIndeterminate = []
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="less" scoped>
.tips {
  background: #d8e8f8;
  color: #047bb3;
  font-size: 0.2rem;
  margin: 0;
  padding: 0.2rem 0.3rem;
  text-align: center;
  font-weight: normal;
}

/deep/ .van-goods-action {
  background: #fff;
  .van-checkbox {
    padding-left: 15px;
    padding-right: 15px;
    align-self: center;
  }
  & ~ .placeholder {
    height: 100px;
  }
}

.card-goods {
  &-box {
    background-color: #fff;
    align-items: center;
    align-content: space-between;
    box-sizing: border-box;
    display: flex;
    justify-content: center;
    overflow: hidden;
    width: 100%;
    flex-wrap: nowrap;
    margin-bottom: 10px;
  }

  /deep/ .van-card:not(:first-child) {
    margin: 0;
  }

  /deep/ .van-card {
    -webkit-box-flex: 1;
    -webkit-flex: 1;
    flex: 1;
    background: #fff;
    padding-left: 0;
    &__footer {
      padding-right: 15px;
      padding-left: 100px;
      right: 0;
      bottom: 10px;
      width: 100%;
      .flexbox {
        > * {
          -webkit-box-flex: 1;
          -webkit-flex: 1;
          flex: 1;
        }
        .price-cny {
          font-size: 16px;
        }
        .price-cny:before {
          vertical-align: top;
        }
      }
      .van-button {
        margin: 0;
        width: 30px;
        height: 30px;
        border-radius: 0;
      }
    }
    .van-cell {
      margin: 5px 0;
      padding: 2px 10px;
      background: #f5f5f5;
      &__right-icon {
        transform: rotate(90deg);
        -ms-transform: rotate(90deg);
        -moz-transform: rotate(90deg);
        -webkit-transform: rotate(90deg);
        -o-transform: rotate(90deg);
      }
    }
  }
  .cart-item-edit {
    display: flex;
    align-items: center;
    justify-content: space-between;
    /deep/ .van-button {
      min-width: auto;
      border: none;
      margin: 0;
      width: 30px;
      height: 30px;
      border-radius: 0;
    }
  }

  &__item {
    position: relative;
    text-align: center;
    /deep/ .van-checkbox {
      display: block;
      &__label {
        display: none;
      }
    }

    /deep/ .van-checkbox__icon {
      padding: 44px 15px;
      height: auto;
    }

    .van-card__price {
      color: #f44;
    }
  }
}
</style>
